﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;

namespace BitworkStudios.Scraper.Document
{
    public static class EnumerableExtension
    {
        public static IEnumerable<Element> ClearElements(this IEnumerable<Element> source)
        {
            var clearElements = source as Element[] ?? source.ToArray();
            foreach (Element element in clearElements)
            {
                element.Value = String.Empty;
            }

            return clearElements;
        }

        public static void SaveToCsv<T>(this IEnumerable<T> data, string filePath) where T : class
        {
            using (var csvWriter = new CsvWriter(new StreamWriter(filePath)))
            {
                //csvWriter.WriteHeader<T>();
                csvWriter.WriteRecords(data);
            }
        }

        public static DataTable ToDataTable<T>(this IEnumerable<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }

            object[] values = new object[props.Count];

            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }

            return table;
        }
    }
}
